// pages/equipmentListElec/equipmentListElec.js
import Toast from '../../miniprogram_npm/@vant/weapp/toast/toast';
const app = getApp();
import CommonService from '../../utils/service/commonService.js';
const util = require('../../utils/util');
//去掉尾部的0 
const regexp=/(?:\.0*|(\.\d+?)0+)$/;
import Base64 from '../../utils/Base64.js';

Page({

  /**
   * 页面的初始数据
   */
  data: {
    //图片前缀
    prefix:'http://bangnizu.oss-cn-hangzhou.aliyuncs.com/bangni/images/',
    //充电报警
    showWarn:false,
    //设备维修中
    showRepairn:false,   
    //删除确认框
    showDelete:false, 
    //搜索词
    searchValue:'',
    //设备列表
    list:[], 
    //要删除的设备id
    deleteId:null,
    //登录的客户信息
    userInfo:{},
    //页码
    page:1,
    //无更多数据了
    notMore: true,
    //无数据
    showNothing:false,
    //设备id集合（用于查询某个项目下的设备）
    idArr:[],
    //显示操作窗口
    show:false,
    //点击列表操作按钮时，需要的对象。
    checkedItem:{},
    //imei数组
    imeiArr:[],
    //设备编码数组
    equipmentNoArr:[],
    //用户权限
    authority:null,
    //是否是安装人员
    isInstaller:false,
    //显示操作窗口
    showButton:false,
    //业务类型选择数据
    businessTypeList:[],
    //搜索词本地存储
    showSearch:false,  
    searchList:[],
    //主题
    theme:app.globalData.theme,
    //是否显示售后功能
    commonShowAfter: true
  },  

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    //获取设备列表数据-公众号跳转
    if(options.imei){
      console.log('公众号传参');
      console.log(options.imei);  

      //字符串截取为数组
      let imeis=options.imei.split(',');      
      console.log(imeis);

      let user=app.globalData.userInfo;
      if(user){
        if(user.isIotInstaller==true){
          this.setData({ 
            isInstaller: true
          })
        }
        
        this.setData({ 
          userInfo: user,
          authority: app.globalData.authority,
          //是否显示售后功能
          commonShowAfter: app.globalData.commonShowAfter
        })
    
        //获取设备列表数据
        this.getList(imeis);
        
      }else{
        wx.redirectTo({
          url: "/pages/login/login?imei="+imeis+"&equipmentElec="+"1"
        })
      }

    }else{
      this.setData({ 
        showNothing: true
      })
    }
  }, 

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    
  },
  
  //处理传参数据
  getEquipmentIds(fromProject){
    let arr=fromProject.equipmentIds;
    let idArr=[];
    for(let i=0;i<arr.length;i++){
      idArr.push(arr[i].id);
    }
    this.setData({ 
      idArr: idArr
    })    
  },   

  //跳转添加设备
  goToAdd(){    
    wx.navigateTo({
			url: "/pages/equipmentAdd/equipmentAdd"
		})
  }, 
  
  //跳转修改设备
  goToEdit(e){ 
    let detail=e.currentTarget.dataset.detail;
    console.log(detail);
    wx.navigateTo({
			url: "/pages/equipmentAdd/equipmentAdd?equipmentId="+detail.id
    })
  }, 

  //跳转物联网信息
  goToIot(e){
    let detail = this.data.checkedItem.currentTarget.dataset.detail;
    wx.navigateTo({
			url: "/pages/iotEquipmentDetail/iotEquipmentDetail?imei="+detail.imei
    })  
  },

  //跳转财务报表
  goToFinancial(e){
    let detail=this.data.checkedItem.currentTarget.dataset.detail;
    wx.navigateTo({
			url: "/pages/financialStatements/financialStatements?info="+ JSON.stringify(detail)
    })     
  },

  //跳转维修工单
  goToRepair(){
    let detail=this.data.checkedItem.currentTarget.dataset.detail;

    let obj={
      equipmentId: detail.id
    }

    wx.navigateTo({
			url: "/packageA/pages/repairList/repairList?paramObj="+JSON.stringify(obj)
    })  
  },
  
  //跳转耗材工单
  goToConsumables(){
    let detail=this.data.checkedItem.currentTarget.dataset.detail;

    let obj={
      equipmentId: detail.id
    }

    wx.navigateTo({
      url: "/packageA/pages/consumableList/consumableList?paramObj="+JSON.stringify(obj)
    })
  },

  //跳转原报修记录
  goToRepair2(e){     
    let detail=this.data.checkedItem.currentTarget.dataset.detail;
    wx.navigateTo({
			url: "/pages/repairRecord/repairRecord?equipmentId="+detail.id+'&equipmentNo='+detail.equipmentNo
    })  
  },  
  
  //获取设备列表数据
  getEquipmentList(){
    Toast.loading({
      duration: 0,
      forbidClick: true,
      message: '加载中...'
    });

    let user=app.globalData.userInfo;
    let param = {
      searchKey: this.data.searchValue,
      page: {
        page:this.data.page,
        pageSize:10
      },
      selectFields:["id","isIotModelOld","imeiObj","iconUrl","member","project","memberTypeName","equipmentNo","equipmentAlias","runtimeToday","workUnit","workAmount","memberType","state","memberId","factoryId","dealerId","fenceId","createDate","oldImei","orderNo","businessType","orderDetailInedx","orderDetailId","purchaseOrderId","isfactoryBindNew","warrantyPeriodEndDate"]
    }

    if(!this.data.idArr.length && !this.data.imeiArr.length && !this.data.equipmentNoArr.length){      
      // if(user){
      //   let isAll = false;
      //   user.roles.forEach(role => {
      //     if(role.appId.indexOf(3)!=-1 && role.dataAuthOfRole.key == 'all') {
      //       isAll = true;
      //     }
      //   })
      //   if (isAll) {
      //     param.checkAuthDepart = false;
      //   } else {
      //     param.authDeparts = user.dataAuthorityOfUser.depart;
      //     if(user.isInstaller&&user.installDepart) {
      //       util.uniqueConcat(param.authDeparts, user.installDepart);
      //     }
      //   }
      // }
    }else{
      //param.checkAuthDepart = false;      
      if(this.data.idArr.length){
        let arrSet=new Set(this.data.idArr);
        param.ids=Array.from(arrSet);
      }
  
      if(this.data.imeiArr.length){
        param.imeis=this.data.imeiArr;
      }
  
      if(this.data.equipmentNoArr.length){
        param.equipmentNos=this.data.equipmentNoArr;
      }
    }
    
    CommonService.goFindEquipmentList(param).then(res=>{
      Toast.clear();
      if(res.data.data && res.data.data.result && res.data.data.count){
        let result=res.data.data.result;
        let bList=this.data.businessTypeList;

        if(result.length){
          result.forEach(item => {
            //处理图片
            if(item.iconUrl){
              item.iconUrlStr=item.iconUrl;
            }else if(item.memberType.length && item.memberType[0].iconUrl){
              item.iconUrlStr=item.memberType[0].iconUrl;
            }
            //图片url去掉乱码
            if(item.iconUrlStr && (item.iconUrlStr.indexOf("?")!=-1)){
              let index = item.iconUrlStr.indexOf("?");
              if (index != -1) {
                item.iconUrlStr = item.iconUrlStr.substring(0, index); 
              }
            }

            //运行时间
            if(item.runtimeToday.length && item.runtimeToday[0].runtime){
              let runtime=item.runtimeToday[0].runtime;
              item.runningTime=(runtime/1000/60/60).toFixed(1).replace(regexp,'$1');
            }else{
              item.runningTime=0;
            } 
            
            //处理清洁面积/清洁里程显示的文字
            if(item.workUnit=='km'){
              item.cleanStr='里程';
            }else{
              item.cleanStr='面积';
            }

            //计算清洁面积
            let areaOne=0;
            if(item.workAmount){
              areaOne=item.workAmount;
            }else if(item.memberType.length && item.memberType[0].cleanArea){
              areaOne=item.memberType[0].cleanArea;
            }
            item.area=Math.round(areaOne*item.runningTime); 
            
            //处理别名
            let aliasArr=[]; 
            let m,p,n;
            if(item.member && item.member.length && item.member[0].nickName){
              m=item.member[0].nickName;
              aliasArr.push(m);
            }
            if(item.project && item.project.length && item.project[0].nickName){
              p=item.project[0].nickName;
              aliasArr.push(p);
            }
            if(item.memberTypeName){
              n=item.memberTypeName
              aliasArr.push(n);
            }
            if(m || p || n){
              aliasArr.push(item.equipmentNo);
              item.alias=aliasArr.join('-');
            }
            
            //处理电量
            if(item.imeiObj.length){
              let vol=item.imeiObj[0].vol,
              maxvol=item.imeiObj[0].maxvol,
              minvol=item.imeiObj[0].minvol;
            
              if(vol==null || vol<=0){
                item.remainingElectricity=0;
              }else if(vol!=null && vol-minvol==0){
                item.remainingElectricity=0;
              }else if(maxvol-minvol==0){
                item.remainingElectricity=100;
              }else if(vol==maxvol && vol==minvol && maxvol==minvol){
                item.remainingElectricity=100;
              }else{
                let str=(((vol-minvol)/(maxvol-minvol)*100).toFixed(2)).replace(regexp,'$1');
                if(str && !isNaN(str)){ 
                  let remainingElectricity=Number(new String(str));
                  if(remainingElectricity<0){
                    item.remainingElectricity=0;
                  }else if(remainingElectricity>100){
                    item.remainingElectricity=100;
                  }else{
                    item.remainingElectricity=remainingElectricity;
                  }
                }
              }
            }

            //处理修改权
            if(item.editerIds && item.editerIds.length){
              let editArr=item.editerIds;
              let departId=app.globalData.userInfo.depart;
              if (editArr.indexOf(departId)!=-1){
                item.edited=true;
              }
            }

            //处理在线/离线
            if(item.imeiObj && item.imeiObj.length && item.imeiObj[0].ctm){
              let ctm=item.imeiObj[0].ctm;
              if(ctm.indexOf('T')==-1){
                ctm=new Date(ctm.replaceAll('-','/'));
              }else{
                ctm=new Date(ctm);
              }              
              
              let currentTime=new Date();
              let num=currentTime-ctm;

              //当前时间大于数据日期16分钟是离线
              if(num>16*60*1000){
                item.onLineJudge=false;
              }else{
                item.onLineJudge=true;
              }

              //当前时间大于数据日期24小时时，显示“离线24小时”并改变背景色
              if(num>24*60*60*1000){
                item.offLine=true;
              }else{
                item.offLine=false;
              }

            }else{
              item.onLineJudge=false;
              item.offLine=false;
            }

            //处理创建日期
            if(item.createDate){
              item.createDate=util.timeFormat(item.createDate);
            }

            //处理质保期
            if(item.warrantyPeriodEndDate){
              item.warrantyPeriodEndDate=util.timeFormat(item.warrantyPeriodEndDate);
            }

            //处理业务类型显示名称
            if(item.businessType){
              bList.forEach(item2 => {
                if(item2.id==item.businessType){
                  item.businessTypeName=item2.text;
                }
              });
            }
              
          });          

          //过滤无信息数据
          if(app.globalData.isShowNo){
            this.setData({ 
              list: this.data.list.concat(result)
            })                       
          }else{
            let newResult=[];
            result.forEach(item => {
              if(item.iconUrlStr && item.project.length){
                newResult.push(item);
              }
            });
            this.setData({ 
              list: this.data.list.concat(newResult)
            }) 
          }

          console.log('设备列表');
          console.log(result);
          
        }else{
          this.setData({
            notMore: false
          })
          if(this.data.page==1){
            this.setData({ 
              showNothing: true
            })
          }else{
            Toast.fail('没有更多了');
          }
        }
      }else{
        if(this.data.page==1){
          this.setData({ 
            showNothing: true
          })
        }
       }
    }).catch((error) => {
      Toast.clear();
      this.setData({ 
        showNothing: true
      })        
    })
  },

  //通过imei获取列表
  getList(imeis){
    Toast.loading({
      duration: 0,
      forbidClick: true,
      message: '加载中...'
    });

    let param = {
      isAuth: true,
      className: 'equipment',
      data: {
        imei: imeis,
        //imei: ['868120292320642','868120246397571'],
        selectFields: ["id","iconUrl","member","project","equipmentNo","imei"],
        sort: {
          id: -1
        },
        page: {
          page: this.data.page,
          pageSize: 10
        },
        nbl: Base64.encode(util.timeFormatDay(new Date()))
      }
    }

    CommonService.goFindList(param).then(res => {
      if(res.data.data && res.data.data.result && res.data.data.result.length) {
        let result=res.data.data.result;
        console.log('低电设备列表');
        console.log(result);

        this.setData({
          list: this.data.list.concat(result)
        })
        Toast.clear();

      }else{
        this.setData({
          notMore: false
        })
        if(this.data.page==1){
          this.setData({
            showNothing: true
          })
          Toast.clear();
        }else{
          Toast.fail('没有更多了');
        }
      }

    }).catch((error) => {
      this.setData({
        showNothing: true
      })
      Toast.clear();
    })
  },

  //刷新列表和页码
  refreshListAndPage(){
    this.setData({ 
      list: [],
      page:1,
      notMore: true,
      showNothing: false      
    })
    //this.getEquipmentList();
    this.getList();
  },  

  //搜索输入时
  onChangeSearch(e){
    this.setData({ 
      searchValue: e.detail.value
    })   
  },

  //点击搜索
  onSearch() {
    this.setData({
      idArr:[],
      imeiArr:[],
      equipmentNoArr:[]
    })

    //刷新列表和页码
    this.refreshListAndPage();

    //将搜索词存入本地
    let searchValue=this.data.searchValue;
    if(searchValue){
      try {
        let arr=[];
        if(wx.getStorageSync('searchs')){
          arr=wx.getStorageSync('searchs');
        }
  
        arr.push(searchValue.trim()); 
        
        //去重
        let arrSet=new Set(arr);
        arr=Array.from(arrSet);
  
        //只存10条
        let arr1=[];
        if(arr.length>10){
          arr1=arr.slice(1);
        }else{
          arr1=arr;
        }
       
        wx.setStorageSync("searchs",arr1);      
      } catch (e) {}
    }
  },

  //搜索框聚焦时
  onFocusSearch(){
    try {
      let arr=wx.getStorageSync('searchs');
      if(arr && arr.length){
        arr.reverse();
        this.setData({
          showSearch:true,
          searchList: arr
        })
      } 
    } catch (e) {}
  },

  //搜索框失去焦点时
  onBlurSearch(){
    setTimeout(() => {
      this.setData({
        showSearch:false
      })
    }, 300)
  },

  //点击搜索词
  onGetSearch(e){
    let val=e.currentTarget.dataset.detail;
    this.setData({ 
      searchValue: val
    })
  },

  //显示删除设备确认框
  onDelete(e){
    let detail=e.currentTarget.dataset.detail;
    this.setData({ 
      showDelete: true,
      deleteId:detail.id
	})    
  },

  //隐藏删除设备确认框
  onCloseDelete(){
    this.setData({ 
			showDelete: false
		})
  },

  //确认删除
  confirmDelete(){
    let param={
      className:"equipment",
      data:{  
        id:this.data.deleteId
      }
    }

    CommonService.goDelete(param).then(res=>{
      if (res.statusCode == 200 && res.data.success == true){
        Toast.success('已删除');
        //刷新列表和页码
        this.refreshListAndPage();
        this.deleteToElastic(this.data.deleteId);
      }else{
        Toast.fail('操作失败');
      }
    }).catch((error) => {
      Toast.fail('操作失败');
    })
  },  
  
  deleteToElastic(id){
    let param={
      equipmentId:id
    }
    CommonService.deleteToElastic(param).then(res=>{
    }).catch((error) => {
    })
  },
  //跳转检测
  goToCheck(e){  
    let detail=this.data.checkedItem.currentTarget.dataset.detail;

    let memberTypeName='暂无信息';
    if(detail.memberTypeName){
      memberTypeName=detail.memberTypeName;
    }else if(detail.memberType.length){
      memberTypeName=detail.memberType[0].name
    }

    let obj={
      imei:detail.imei,
      type:memberTypeName
    }
    
    wx.navigateTo({
      url: "/pages/check/check?detail="+JSON.stringify(obj)
    })
  },    

  //跳转电池曲线
  goToBattery(e){
    let detail=this.data.checkedItem.currentTarget.dataset.detail;
    let obj={
      imei:detail.imei,
      equipmentNo:detail.equipmentNo
    }
    wx.navigateTo({
      url: "/packageA/pages/batteryStatistics/batteryStatistics?detail="+JSON.stringify(obj)
    }) 
  },

  //跳转物联网数据日志
  goToLog(e){
    let detail=this.data.checkedItem.currentTarget.dataset.detail;
    wx.navigateTo({
      url: "/pages/iotLog/iotLog?imei="+detail.imei
    })
  },  

  //点击筛选按钮
  onScreen(){
    app.globalData.isShowNo=!app.globalData.isShowNo;
    this.refreshListAndPage();
  }, 
  
  //跳转充电记录
  goToCharge(){
    let detail=this.data.checkedItem.currentTarget.dataset.detail;
    wx.navigateTo({
      url: "/pages/charge/charge?imei="+detail.imei
    })
  },

  //跳转检修
  goToOverhaul(){
    let detail=this.data.checkedItem.currentTarget.dataset.detail;    
    let paramObj={
      projectId:detail.project.length ? detail.project[0].id : null,
      equipmentId:detail.id,
      projectName:detail.project.length ? detail.project[0].name : '暂无项目信息',
      equipmentName:detail.memberTypeName,
    }
    wx.navigateTo({
      url: "/pages/overhaul/overhaul?paramObj="+JSON.stringify(paramObj)
    })
  },
  
  //跳转物联网异常
  goToException(){
    let detail=this.data.checkedItem.currentTarget.dataset.detail;
    let obj={
      imei:detail.imei,
      dataAuthority:detail.dataAuthority.depart
    }
    wx.navigateTo({
      url: "/packageA/pages/iotException/iotException?paramFrom="+JSON.stringify(obj)
    })
  },

  //跳转安装信息
  goToInstall(){
    let detail=this.data.checkedItem.currentTarget.dataset.detail;
    let obj={
      equipmentId: detail.id,
      imei: detail.imei
    }
    wx.navigateTo({
      url: "/packageA/pages/iotInstall/iotInstall?paramObj="+JSON.stringify(obj)
    }) 
  },

  //显示功能区按钮
  showOptions: function(e){
    this.setData({
      showButton: true,
      checkedItem: e
    })    
  },

  //隐藏功能区按钮
  onCloseButton:function(){
    this.setData({
      showButton:false
    })
  },

  //跳转围栏页面
  goToFence(){
    let detail=this.data.checkedItem.currentTarget.dataset.detail;
    let obj={
      imei: detail.imei,
      fenceId: detail.fenceId ? detail.fenceId : null
    }
    wx.navigateTo({
      url: "/packageA/pages/setEquipmentFence/setEquipmentFence?paramObj="+JSON.stringify(obj)
    })
  },

   //迁移数据
   goToMove(){
    let detail=this.data.checkedItem.currentTarget.dataset.detail;
    console.log(detail);
  },

  //培训报告
  goToTrain(){
    let detail=this.data.checkedItem.currentTarget.dataset.detail;
    
    let obj={
      orderNo: detail.orderNo,
      equipmentNo: detail.equipmentNo
    }  

    wx.navigateTo({
      url: "/packageA/pages/trainReportList/trainReportList?paramObj="+JSON.stringify(obj)
    })
  },

  //不工作原因上报
  goToNotWork(){
    let detail=this.data.checkedItem.currentTarget.dataset.detail;

    let obj={
      imei: detail.imei,
      equipmentNo: detail.equipmentNo,
      equipmentId: detail.id
    }

    wx.navigateTo({
      url: "/packageA/pages/notWorkList/notWorkList?paramObj="+JSON.stringify(obj)
    })  
  },

  //跳转模块作废
  goToVoid(){
    let detail=this.data.checkedItem.currentTarget.dataset.detail;

    let obj={
      imei: detail.imei,  
      equipmentId: detail.id
    }

    wx.navigateTo({
      url: "/packageA/pages/iotVoidList/iotVoidList?paramObj="+JSON.stringify(obj)
    })  
  },

  //跳转添加维修工单
  goToRepairAdd({currentTarget}){
    let detail=currentTarget.dataset.detail;

    let obj={
      equipmentId: detail.id,
      repairType: 216
    }

    wx.navigateTo({
			url: "/pages/repairAdd/repairAdd?paramObj="+JSON.stringify(obj)
		})  
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   *
  onReady: function () {

  },
  
  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
    
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
    if (this.data.notMore) {
      this.data.page = this.data.page + 1;
      //this.getEquipmentList(); 
      this.getList();   
    }
  },
  
  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})